package com.woniu.mp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mp.entity.CategoryEntity;
import com.woniu.mp.mapper.CategoryDao;
import com.woniu.mp.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    /**
     * 树形数据还可以这样组装？真优雅！
     */
    public List<Tree<Long>> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        if (!CollectionUtil.isEmpty(entities)) {
            List<TreeNode<Long>> list = entities.
                    stream().
                    map(CategoryServiceImpl::getLongTreeNode).
                    collect(Collectors.toList());
            return TreeUtil.build(list, 0L);
        }
        return Collections.emptyList();
    }

    private static TreeNode<Long> getLongTreeNode(CategoryEntity item) {
        TreeNode<Long> treeNode = new TreeNode<>();
        treeNode.setId(item.getCatId());
        treeNode.setParentId(item.getParentCid());
        treeNode.setName(item.getName());
        treeNode.setWeight(item.getSort());
        Map<String, Object> extra = new HashMap<>();
        extra.put("showStatus", item.getShowStatus());
        extra.put("catLevel", item.getCatLevel());
        extra.put("icon", item.getIcon());
        extra.put("productUnit", item.getProductUnit());
        extra.put("productCount", item.getProductCount());
        treeNode.setExtra(extra);
        return treeNode;
    }


}